package com.cloudlegal.controller;

import com.cloudlegal.common.Result;
import com.cloudlegal.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * JWT测试控制器
 * 用于测试JWT配置和功能
 * 
 * @author CloudLegal Team
 * @since 2024-01-01
 */
@Tag(name = "JWT测试", description = "JWT配置和功能测试接口")
@RestController
@RequestMapping("/test/jwt")
public class JwtTestController {

    @Autowired
    private JwtUtils jwtUtils;

    @Operation(summary = "获取JWT密钥信息", description = "获取当前JWT密钥的安全信息")
    @GetMapping("/key-info")
    public Result<Map<String, Object>> getKeyInfo() {
        Map<String, Object> keyInfo = jwtUtils.getKeyInfo();
        return Result.success(keyInfo);
    }

    @Operation(summary = "验证密钥强度", description = "验证JWT密钥是否满足HS512算法要求")
    @GetMapping("/validate-key")
    public Result<Map<String, Object>> validateKey() {
        boolean isValid = jwtUtils.validateKeyStrength();
        Map<String, Object> result = Map.of(
            "isValid", isValid,
            "algorithm", "HS512",
            "minRequiredBits", 512,
            "message", isValid ? "密钥强度满足要求" : "密钥强度不足，请使用至少64字节的密钥"
        );
        return Result.success(result);
    }

    @Operation(summary = "生成测试Token", description = "生成用于测试的JWT Token")
    @PostMapping("/generate-token")
    public Result<Map<String, Object>> generateTestToken(
            @RequestParam(defaultValue = "1") Long userId,
            @RequestParam(defaultValue = "testuser") String username,
            @RequestParam(defaultValue = "1") Long roleId,
            @RequestParam(defaultValue = "30") int expireMinutes) {
        
        try {
            // 使用分钟生成Token
            String token1 = jwtUtils.createTestToken(userId, username, roleId, expireMinutes);
            
            // 使用TimeUnit生成Token
            String token2 = jwtUtils.createTestToken(userId, username, roleId, 1);
            
            // 生成访问Token和刷新Token
            Map<String, Object> claims = Map.of(
                "userId", userId,
                "username", username,
                "roleId", roleId
            );
            String accessToken = jwtUtils.generateAccessToken(claims);
            String refreshToken = jwtUtils.generateRefreshToken(claims);
            
            Map<String, Object> result = Map.of(
                "tokenByMinutes", token1,
                "tokenByTimeUnit", token2,
                "accessToken", accessToken,
                "refreshToken", refreshToken,
                "expireMinutes", expireMinutes,
                "userId", userId,
                "username", username,
                "roleId", roleId
            );
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("生成Token失败: " + e.getMessage());
        }
    }

    @Operation(summary = "验证Token", description = "验证JWT Token的有效性")
    @PostMapping("/validate-token")
    public Result<Map<String, Object>> validateToken(@RequestParam String token) {
        try {
            boolean isValid = jwtUtils.validateToken(token);
            boolean isExpired = jwtUtils.isTokenExpired(token);
            Long userId = jwtUtils.getUserIdFromToken(token);
            String username = jwtUtils.getUsernameFromToken(token);
            long remainingSeconds = jwtUtils.getTokenRemainingTime(token);
            long remainingMinutes = jwtUtils.getTokenRemainingTime(token);
            long remainingHours = jwtUtils.getTokenRemainingTime(token);
            
            Map<String, Object> result = Map.of(
                "isValid", isValid,
                "isExpired", isExpired,
                "userId", userId != null ? userId : "N/A",
                "username", username != null ? username : "N/A",
                "remainingSeconds", remainingSeconds,
                "remainingMinutes", remainingMinutes,
                "remainingHours", remainingHours,
                "message", isValid ? "Token有效" : "Token无效或已过期"
            );
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("验证Token失败: " + e.getMessage());
        }
    }

    @Operation(summary = "刷新Token", description = "刷新JWT Token")
    @PostMapping("/refresh-token")
    public Result<Map<String, Object>> refreshToken(
            @RequestParam String token,
            @RequestParam(defaultValue = "60") int newExpireMinutes) {
        
        try {
            String newToken = jwtUtils.refreshToken(token, newExpireMinutes);
            
            if (newToken != null) {
                Map<String, Object> result = Map.of(
                    "originalToken", token,
                    "newToken", newToken,
                    "newExpireMinutes", newExpireMinutes,
                    "message", "Token刷新成功"
                );
                return Result.success(result);
            } else {
                return Result.error("Token刷新失败，原Token可能无效");
            }
        } catch (Exception e) {
            return Result.error("刷新Token失败: " + e.getMessage());
        }
    }

    @Operation(summary = "Token性能测试", description = "测试JWT Token生成和验证性能")
    @GetMapping("/performance-test")
    public Result<Map<String, Object>> performanceTest(
            @RequestParam(defaultValue = "1000") int iterations) {
        
        try {
            Map<String, Object> claims = Map.of(
                "userId", 1L,
                "username", "testuser",
                "roleId", 1L
            );
            
            // 测试Token生成性能
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < iterations; i++) {
                jwtUtils.generateToken(claims, 30);
            }
            long generateTime = System.currentTimeMillis() - startTime;
            
            // 生成一个Token用于验证测试
            String testToken = jwtUtils.generateToken(claims, 30);
            
            // 测试Token验证性能
            startTime = System.currentTimeMillis();
            for (int i = 0; i < iterations; i++) {
                jwtUtils.validateToken(testToken);
            }
            long validateTime = System.currentTimeMillis() - startTime;
            
            Map<String, Object> result = Map.of(
                "iterations", iterations,
                "generateTimeMs", generateTime,
                "validateTimeMs", validateTime,
                "avgGenerateTimeMs", (double) generateTime / iterations,
                "avgValidateTimeMs", (double) validateTime / iterations,
                "tokensPerSecond", (int) (iterations * 1000.0 / generateTime),
                "validationsPerSecond", (int) (iterations * 1000.0 / validateTime)
            );
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("性能测试失败: " + e.getMessage());
        }
    }
}
